import Taro from "@tarojs/taro";
import { getStore } from "./localStore";

export const baseUrl = "https://yxxf.guojutech.net/api";
// export const baseUrl = "http://172.18.10.13:15050";

export const baseUploadUrl = `${baseUrl}/mini/v1/storage/upload?dir=`;

// const token =
//   "BearereyJhbGciOiJIUzI1NiJ9.eyJzeXNPcmdOYW1lIjpudWxsLCJyb2xlcyI6bnVsbCwibmFtZSI6bnVsbCwibG9naW5Db2RlIjpudWxsLCJpZCI6IjEiLCJleHAiOjE2OTU5NTE3MDl9.ynw5HEkCF1VrHnox-DuQELhsFlLQWR2KqxedRRvsTp0";

// interface ApiResult<T> {
//   success: boolean;
//   code: number;
//   msg: string;
//   data: T;
// }

// 网络请求拦截器
const interceptor = function (chain) {
  const requestParams = chain.requestParams;
  // const { method, data } = requestParams;
  //
  // if (method === "GET") {
  //   if (data) {
  //     requestParams.url =
  //       requestParams.url +
  //       "?" +
  //       decodeURIComponent(qs.stringify(requestParams.data));
  //     requestParams.data = undefined;
  //   }
  // }

  return chain.proceed(requestParams).then((res) => {
    return res;
  });
};

Taro.addInterceptor(interceptor);

const request = (method, url, params, config) => {
  //由于post请求时习惯性query参数使用params，body参数使用data，而taro只有data参数，使用contentType作为区分，因此此处需要做一个判断

  return new Promise((resolve, reject) => {
    Taro.request({
      method: method || "GET",
      isShowLoading: true,
      url: `${baseUrl}${url}`,
      data: params || {},
      header: {
        "content-type": "application/json",
        "x-auth-token": getStore("token"),
      },
      timeout: 5000,
      ...config,
      success: (res) => {
        if (res?.statusCode === 200) {
          if (res?.data?.code === 401) {
            Taro.clearStorageSync();
            Taro.reLaunch({
              url: "/pages/login/login",
            });
            return;
          }

          resolve(res?.data);
          return;
        }

        if (res?.statusCode === 404) {
          Taro.showToast({
            title: "请求连接异常!",
            icon: "error",
          });
          reject(res);
          return;
        }
      },
      fail: (e) => {
        Taro.showToast({
          title: e.errMsg.includes("timeout") ? "请求超时!" : "请求异常!",
          icon: "error",
        });
        reject(e);
      },
    });
  });
};

export const get = (url, params, config) => {
  return request("GET", url, params, config);
};

export const post = (url, params, config) => {
  return request("POST", url, params, config);
};

export const put = (url, params, config) => {
  return request("PUT", url, params, config);
};

export const del = (url, params, config) => {
  return request("DELETE", url, params, config);
};

export const uploadFile = (dir, filePath) => {
  return new Promise((resolve, reject) => {
    Taro.uploadFile({
      url: `${baseUrl}/mini/v1/storage/upload?dir=${dir}`, //仅为示例，非真实的接口地址
      filePath,
      name: "file",
      header: { "x-auth-token": getStore("token") },
      success: (res) => {
        if (res?.statusCode === 200) {
          resolve(JSON.parse(res?.data));
          return;
        }

        if (res?.statusCode === 404) {
          Taro.showToast({
            title: "上传错误!",
            icon: "error",
          });
          reject(res);
          return;
        }

        Taro.showToast({
          title: "上传错误!",
          icon: "error",
        });
        reject(res);
      },
      fail: (error) => {
        console.log(error);
        reject();
      },
    });
  });
};

export const uploadFileList = (dir, filePath) => {
  return new Promise((resolve, reject) => {
    Taro.uploadFile({
      url: `${baseUrl}/mini/v1/storage/batchUpload?dir=${dir}`, //仅为示例，非真实的接口地址
      filePath:filePath,
      name: "file",
      header: { "x-auth-token": getStore("token") },
      success: (res) => {
        if (res?.statusCode === 200) {
          resolve(JSON.parse(res?.data));
          return;
        }

        if (res?.statusCode === 404) {
          Taro.showToast({
            title: "上传错误!",
            icon: "error",
          });
          reject(res);
          return;
        }

        Taro.showToast({
          title: "上传错误!",
          icon: "error",
        });
        reject(res);
      },
      fail: (error) => {
        console.log(error);
        reject();
      },
    });
  });
};
